<?php
date_default_timezone_set('Asia/Shanghai');
header('Content-Type:text/html;charset=utf-8');
define('SVN_BASEURL', 'http://qhz.googlecode.com/svn/trunk/fms');
define('FTP_BASEDIR', dirname(__FILE__));

function get_files($dir, $type)
{
	$result = array();

	if ($type === 'ftp')
	{
		$files = ftp_scan_dir($dir);
	}
	elseif ($type === 'svn')
	{
		$files = svn_scan_dir($dir);
	}
	else
	{
		return;
	}

	foreach ($files as $file)
	{
		if ($file['is_dir'])
		{
			$temp = get_files($dir.$file['name'], $type);
			$result = array_merge($result, $temp);
		}
		else
		{
			$result[] = $dir.$file['name'];
		}
	}

	return $result;
}


function svn_scan_dir($dir)
{
	$content = file_get_contents(SVN_BASEURL.$dir);
	preg_match_all('/<li><a href="(.*?)">/', $content, $matches);
	$match = isset($matches[1]) ? $matches[1] : array();

	$files = array();
	foreach ($match as $item)
	{
		if ($item === '../')
		{
			continue;
		}
		$file = array();
		$file['name'] = $item;
		$file['is_dir'] = strpos($item, '/') > 0 ? true : false;

		$files[] = $file;
	}

	return $files;
	
}

function ftp_scan_dir($dir)
{
	$real_dir = FTP_BASEDIR.$dir;
	$scandir = scandir($real_dir);

	$files = array();
	foreach ($scandir as $item)
	{
		if ($item[0] === '.')
		{
			continue;
		}
		$file = array();
		$file['is_dir'] = is_dir($real_dir.$item);
		$file['name'] = $file['is_dir'] ? $item.'/' : $item;
		
		$files[] = $file;
	}

	return $files;
}

function update_file($file)
{
	$svn_url = SVN_BASEURL.$file;
	$ftp_path = FTP_BASEDIR.$file;

	$source = file_get_contents($svn_url);
	
	file_put_contents($ftp_path, $source);
}

//////////////////////////////////////////////////////////
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$type = isset($_GET['svn']) ? 'svn' : 'ftp';

if ($dir === '')
{
	exit('请指定dir！');
}

if (substr($dir, -1) !== '/')
{
	$files = array($dir);
}
else
{
	$files = get_files($dir, $type);
}


if(isset($_GET['update']))
{
	foreach ($files as $file)
	{
		update_file($file);
		echo '已更新 <b>'.$file.'</b></br>';
	}
}
else
{
	echo '即将更新以下文件(共<b style="color:#f00;">'.count($files).'</b>个)：<hr />';
	foreach ($files as $file)
	{
		echo '<b>'.$file.'</b> ';
		echo is_file(FTP_BASEDIR.$file) ? '<span style="font-size:12px;background:#f00;color:#fff;">已存在</span>' : '<span style="font-size:12px;background:#999;color:#fff;">不存在</span>';
		echo '<br />';
	}
	echo '<hr />';
	echo '<a href="'.$_SERVER['REQUEST_URI'].'&update">点击确认更新</a>';
}
